package org.terramagnet.mvcframework.friendly;

import java.util.IllegalFormatException;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;

/**
 * 友好的错误码配置.
 *
 * @author lip
 *
 * @deprecated 使用{@link I18nFriendly}代替
 */
public enum BuildinFriendly implements Friendly {

    SUCCESS(0, "成功"),
    NULL_RESULT_ERROR(404, "未查找到记录"),
    NOT_ACCEPTABLE(406, "无法解析的请求报文：%s"),
    INVALID_ARGUMENT(400, "%s 参数不合法"),
    INVALID_ENUM_ARGUMENT(400, "参数不合法，%s 的可选值为 %s 之一") {

            @Override
            public String toFriendly(Locale locale, Object... params) throws IllegalFormatException {
                if (params == null || params.length < 2) {
                    return "参数不合法";
                }

                if (params[1] instanceof Class) {
                    Class<?> enumClass = (Class<?>) params[1];
                    if (enumClass.isEnum()) {
                        Object[] enumConstants = enumClass.getEnumConstants();
                        String names = StringUtils.join(enumConstants, '|');
                        return String.format(locale == null ? Locale.getDefault() : locale, getTemplate(), params[0], names);
                    }
                }
                return "参数不合法";
            }

        },
    NOT_SUPPORTED_MOBILE(492, "不支持的手机号码"),
    INVALID_MOBILE_ERROR(489, "无效的手机号码"),
    NOT_FOUND(404, "找不到对象：%s"),
    PASSWORD_TOO_SIMPLE(406, "密码过于简单"),
    PASSWORD_NOT_ACCEPTABLE(403, "旧密码不正确"),
    /* ======================================================================== */
    FAIL(500, "系统繁忙，请稍后再试！"),
    ILLAGE_CHANNEL(403, "非法的接口调用：%s"),
    FAIL_FUNNY(500, "主人，服务器出现了一点小故障，程序猿努力修复中..."),
    FAIL_UNKNOWN(500, "啊哦~好像出了点小故障，请稍后再试！");

    /**
     * 错误码
     */
    private final int code;
    /**
     * 错误信息
     */
    private final String template;

    /**
     * 错误码构造器.
     *
     * @param code 响应码
     * @param message 生产环境下的响应消息
     */
    BuildinFriendly(int code, String message) {
        this.code = code;
        this.template = message;
    }

    /**
     * 从错误码转换. 不识别时返回{@code null}.
     */
    public static BuildinFriendly parseCode(int code) {
        for (BuildinFriendly type : BuildinFriendly.values()) {
            if (type.getCode() == code) {
                return type;
            }
        }
        return null;
    }

    @Override
    public int getCode() {
        return code;
    }

    @Override
    public String getTemplate() {
        return template;
    }

    @Override
    public String toFriendly(Locale locale, Object... params) {
        if (params == null || params.length == 0) {
            return template.replace("%s", "");
        }
        return String.format(locale == null ? Locale.getDefault() : locale, template, params);
    }

    @Override
    public String toString() {
        return toFriendly(null, (Object[]) null);
    }

}
